package test;

import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ContConThread extends Frame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Panel p1 = new Panel();
	private Panel p2 = new Panel();
	private Button onOff = new Button("ON-OFF");
	private Button start = new Button("START");
	private Semaforo sem = new Semaforo();

	private class ThreadCont extends Thread {
		public void run() {
			TextField t = new TextField(4);
			p2.add(t);
			ContConThread.this.setVisible(true);
			int count = 0;
		   while (true) {
			   try {
				   Thread.sleep(100);
			   } catch(InterruptedException e) {}
				t.setText(Integer.toString(count++));
			   sem.passa();
		   }
	   }
	}

	class OnOffL implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			sem.cambia();
		}
	}

	class StartL implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			ThreadCont tc = new ThreadCont();
			tc.start();
		}
	}

	class WL extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	}

	public ContConThread() {
		setLayout(new GridLayout(2,1));
		onOff.addActionListener(new OnOffL());
		p1.add(onOff);
		addWindowListener(new WL());
		start.addActionListener(new StartL());
		p1.add(start);
		add(p1);
		add(p2);
		setSize(300,200);
	   setVisible(true);
		
	}

	public static void main(String args[]) {
      ContConThread f = new ContConThread();
	
   }
}

class Semaforo {
	boolean rosso = false;

	synchronized void passa() {
		while (rosso) 
			try {
				   wait();
			     } catch(InterruptedException e) {}
	}

	synchronized void cambia() {
		rosso = !rosso;
		if (!rosso) notifyAll();
	}
}